/**
 * LoraListSelectorModelOnly 前端支持
 * 提供动态 LoRA 列表过滤功能
 */

import { app } from "../../scripts/app.js";

/**
 * 扩展 LoraListSelectorModelOnly 节点
 */
app.registerExtension({
    name: "ComfyUI-xhh.LoraListSelectorModelOnly",
    
    async beforeRegisterNodeDef(nodeType, nodeData, app) {
        if (nodeData.name === "XHH_LoraListSelectorModelOnly") {
            const origGetExtraMenuOptions = nodeType.prototype.getExtraMenuOptions;
            
            // 添加菜单选项
            nodeType.prototype.getExtraMenuOptions = function(_, options) {
                const r = origGetExtraMenuOptions ? origGetExtraMenuOptions.call(this, options) : options;
                
                r.push({
                    content: "📋 显示过滤后的 LoRA 列表",
                    callback: () => {
                        this.showFilteredLoraList();
                    }
                });
                
                r.push({
                    content: "🔄 刷新 LoRA 列表",
                    callback: () => {
                        this.refreshLoraList();
                    }
                });
                
                return r;
            };
            
            // 显示过滤后的 LoRA 列表
            nodeType.prototype.showFilteredLoraList = function() {
                try {
                    const includeWidget = this.widgets.find(w => w.name === "include");
                    const includePattern = includeWidget ? includeWidget.value : "";
                    
                    // 获取所有 LoRA 文件
                    const allLoras = this.getAllLoraFiles();
                    const filteredLoras = this.filterLoraList(allLoras, includePattern);
                    
                    const message = `过滤后的 LoRA 列表 (${filteredLoras.length} 个):\n\n` + 
                        filteredLoras.slice(0, 20).join('\n') + 
                        (filteredLoras.length > 20 ? `\n... 还有 ${filteredLoras.length - 20} 个` : '');
                    
                    alert(message);
                } catch (error) {
                    console.error("显示 LoRA 列表失败:", error);
                    alert("显示 LoRA 列表失败: " + error.message);
                }
            };
            
            // 刷新 LoRA 列表
            nodeType.prototype.refreshLoraList = function() {
                try {
                    const includeWidget = this.widgets.find(w => w.name === "include");
                    const includePattern = includeWidget ? includeWidget.value : "";
                    
                    const allLoras = this.getAllLoraFiles();
                    const filteredLoras = this.filterLoraList(allLoras, includePattern);
                    
                    console.log(`刷新完成，找到 ${filteredLoras.length} 个 LoRA 文件`);
                    console.log("过滤后的 LoRA 列表:", filteredLoras);
                } catch (error) {
                    console.error("刷新 LoRA 列表失败:", error);
                }
            };
            
            // 获取所有 LoRA 文件
            nodeType.prototype.getAllLoraFiles = function() {
                try {
                    // 从 lora_name 输入中获取所有可用的 LoRA 文件
                    const loraNameWidget = this.widgets.find(w => w.name === "lora_name");
                    if (loraNameWidget && loraNameWidget.options && Array.isArray(loraNameWidget.options)) {
                        return loraNameWidget.options;
                    }
                    
                    // 如果无法获取，返回空数组
                    return [];
                } catch (error) {
                    console.error("获取 LoRA 文件列表失败:", error);
                    return [];
                }
            };
            
            // 过滤 LoRA 列表
            nodeType.prototype.filterLoraList = function(loras, includePattern) {
                if (!includePattern || !includePattern.trim()) {
                    return loras;
                }
                
                const patterns = includePattern.split('\n')
                    .map(line => line.trim())
                    .filter(line => line.length > 0);
                
                if (patterns.length === 0) {
                    return loras;
                }
                
                return loras.filter(lora => {
                    return patterns.some(pattern => {
                        try {
                            const regex = new RegExp(pattern, 'i');
                            return regex.test(lora);
                        } catch (error) {
                            // 如果正则表达式无效，使用简单的字符串包含检查
                            return lora.toLowerCase().includes(pattern.toLowerCase());
                        }
                    });
                });
            };
            
            // 监听 include 输入的变化
            const origOnConfigure = nodeType.prototype.onConfigure;
            nodeType.prototype.onConfigure = function(info) {
                const r = origOnConfigure ? origOnConfigure.call(this, info) : undefined;
                
                // 监听 include 输入的变化
                const includeWidget = this.widgets.find(w => w.name === "include");
                if (includeWidget) {
                    const origCallback = includeWidget.callback;
                    includeWidget.callback = (value) => {
                        if (origCallback) {
                            origCallback.call(includeWidget, value);
                        }
                        
                        // 当 include 模式改变时，自动刷新 LoRA 列表
                        setTimeout(() => {
                            this.refreshLoraList();
                        }, 100);
                    };
                }
                
                return r;
            };
        }
    },
    
    async setup() {
        console.log("ComfyUI-xhh.LoraListSelectorModelOnly 扩展已加载");
    }
});

/**
 * 工具函数：创建正则表达式
 */
function createRegex(pattern) {
    try {
        return new RegExp(pattern, 'i');
    } catch (error) {
        // 如果正则表达式无效，返回 null
        return null;
    }
}

/**
 * 工具函数：检查字符串是否匹配模式
 */
function matchesPattern(text, pattern) {
    const regex = createRegex(pattern);
    if (regex) {
        return regex.test(text);
    } else {
        // 如果正则表达式无效，使用简单的字符串包含检查
        return text.toLowerCase().includes(pattern.toLowerCase());
    }
}

export { createRegex, matchesPattern };
